package com.bank.controller;


import com.bank.auto.JSONAuthentication;
import com.bank.entity.BaDeposit;
import com.bank.entity.BaMeans;
import com.bank.entity.BaRepay;
import com.bank.entity.BaUser;
import com.bank.mapper.BaMeansMapper;
import com.bank.mapper.BaRepayMapper;
import com.bank.mapper.BaUserMapper;
import com.bank.response.Result;
import com.bank.service.BaRepayService;
import com.bank.utils.ExcelUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import jdk.internal.org.objectweb.asm.commons.JSRInlinerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author bank
 * @since 2022-03-16
 */
@RestController
@RequestMapping("/ba-repay")
public class BaRepayController extends JSONAuthentication {
    @Autowired
    BaRepayMapper baRepayMapper;
    @Autowired
    BaUserMapper baUserMapper;
    @Autowired
    BaMeansMapper baMeansMapper;
    @Autowired
    BaRepayService baRepayService;
    @ApiOperation(value = "添加用户贷款的资料。贷款状态，还款金额不要")
    @PostMapping("/add")
    public void addCar(HttpServletRequest request, HttpServletResponse response, @RequestBody BaRepay baRepay) throws Exception {
       QueryWrapper wrapper=new QueryWrapper();
       wrapper.eq("user_id",baRepay.getUserId());
       wrapper.eq("status","待还款");
        BaRepay baRepay1 = baRepayMapper.selectOne(wrapper);
        if(baRepay1!=null){
            Result error = Result.error().message("还有未还的贷款，不可贷款");
            this.WriteJSON(request, response, error);
        }else{
            baRepay.setRepayments(baRepay.getPrice()*baRepay.getReTime()/100+baRepay.getPrice());

            if (baRepayMapper.insert(baRepay) > 0) {
                Result ok = Result.ok();
                this.WriteJSON(request, response, ok);
            } else {
                Result error = Result.error();
                this.WriteJSON(request, response, error);
            }
        }
    }
    @ApiOperation(value = "修改贷款状态，发放贷款")
    @PostMapping("/updRePayStatus")
    public void updRePayStatus(HttpServletRequest request, HttpServletResponse response,@RequestParam("id") int id) throws Exception {
        BaRepay baRepay=baRepayMapper.selectById(id);
        int userId=baRepay.getUserId();
        float daikuanerdu=baRepay.getPrice();
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("user_id",userId);
        BaMeans baMeans = baMeansMapper.selectOne(wrapper);
      if(baMeans!=null){
          float balance=baMeans.getBalance();
          baMeans.setBalance(balance+daikuanerdu);
          baRepay.setStatus("待还款");
          if(baRepayMapper.updateById(baRepay)>0&&baMeansMapper.updateById(baMeans)>0){
              Result ok = Result.ok().message("发放");
              this.WriteJSON(request, response, ok);
          }else{
              Result error = Result.error().message("发放失败");
              this.WriteJSON(request, response, error);
          }
      }else{
          Result error = Result.error().message("请完善个人信息");
          this.WriteJSON(request, response, error);
      }
    }
    @ApiOperation(value = "修改贷款状态，还贷款")
    @PostMapping("/updRePayStatusHk")
    public void updRePayStatusHk(HttpServletRequest request, HttpServletResponse response,@RequestParam("id") int id) throws Exception {
        BaRepay baRepay=baRepayMapper.selectById(id);
        int userId=baRepay.getUserId();
        float huankuanerdu=baRepay.getRepayments();
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("user_id",userId);
        BaMeans baMeans = baMeansMapper.selectOne(wrapper);
        float balance=baMeans.getBalance();
       if(balance-huankuanerdu>0){
           baMeans.setBalance(balance-huankuanerdu);
           baRepay.setStatus("已还款");
           if(baRepayMapper.updateById(baRepay)>0&&baMeansMapper.updateById(baMeans)>0){
               Result ok = Result.ok().message("还款成功");
               this.WriteJSON(request, response, ok);
           }else{
               Result error = Result.error().message("还款失败");
               this.WriteJSON(request, response, error);
           }
       }else{
           Result error = Result.error().message("余额不足");
           this.WriteJSON(request, response, error);
       }
    }
    @ApiOperation(value = "查找所有贷款记录")
    @PostMapping("/findAllRepay")
    public void findAllRepay(HttpServletRequest request, HttpServletResponse response,@RequestParam("size") int size,@RequestParam ("current") int current)throws  Exception{
        Page<BaRepay> shUserPage=new Page<>(current,size);
        Page<BaRepay> shUserPages=baRepayMapper.selectPage(shUserPage,null);
        List<BaRepay> records = shUserPages.getRecords();
        for(BaRepay a:records){
            BaUser baUser=baUserMapper.selectById(a.getUserId());
            QueryWrapper wrapper=new QueryWrapper();
            wrapper.eq("user_id",a.getUserId());
            baUser.setBaMeans(baMeansMapper.selectOne(wrapper));
            a.setBaUser(baUser);
        }
        int total=baRepayMapper.selectCount(null);
        if(records.size()>0){
            Result ok = Result.ok().data("PePay",records).data("total",total);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "根据用户id查找所有贷款记录")
    @PostMapping("/findAllRepayByUserId")
    public void findAllRepay(HttpServletRequest request, HttpServletResponse response,@RequestParam("size") int size,@RequestParam ("current") int current,@RequestParam("userId") int userId)throws  Exception{
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("user_id",userId);
        Page<BaRepay> shUserPage=new Page<>(current,size);
        Page<BaRepay> shUserPages=baRepayMapper.selectPage(shUserPage,wrapper);
        List<BaRepay> records = shUserPages.getRecords();
        int total=baRepayMapper.selectCount(wrapper);
        for(BaRepay a:records){
            BaUser baUser=baUserMapper.selectById(a.getUserId());
            QueryWrapper wrapper1=new QueryWrapper();
            wrapper1.eq("user_id",a.getUserId());
            baUser.setBaMeans(baMeansMapper.selectOne(wrapper1));
            a.setBaUser(baUser);
        }
        if(records.size()>0){
            Result ok = Result.ok().data("PePay",records).data("total",total);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "excel表批量导入数据")
    @PostMapping("/excel")
    public void excel(HttpServletRequest request, HttpServletResponse response,@RequestParam("excel") MultipartFile excelFile)throws  Exception {
        String name=excelFile.getOriginalFilename();
        if(name.length()<6|| !name.substring(name.length()-5).equals(".xlsx")){
            Result error = Result.error().message("输入表格式错误");
            this.WriteJSON(request, response, error);
        }else{
            List<BaRepay> integers = ExcelUtils.excelToShopIdList(excelFile.getInputStream());
            boolean flag=baRepayService.saveBatch(integers);
            if(flag){
                Result ok = Result.ok().message("批量导入成功").data("a",integers);
                this.WriteJSON(request, response, ok);
            }else{
                Result error = Result.error().message("批量导入失败");
                this.WriteJSON(request, response, error);
            }

        }
    }
}

